package com.css.dzj.dzjfxyj.modules.distribute.service.impl;

import com.css.dzj.dzjfxyj.common.util.BeanUtil;
import com.css.dzj.dzjfxyj.common.util.Constant;
import com.css.dzj.dzjfxyj.common.util.R;
import com.css.dzj.dzjfxyj.common.util.ServiceUtil;
import com.css.dzj.dzjfxyj.modules.acquier.entity.JgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.entity.QJgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.service.AcquierService;
import com.css.dzj.dzjfxyj.modules.distribute.entity.JgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.entity.QJgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.mapper.DistributeMapper;
import com.css.dzj.dzjfxyj.modules.distribute.service.DistributeService;
import com.css.dzj.dzjfxyj.modules.distribute.vo.DistributeEditVo;
import com.css.dzj.dzjfxyj.modules.distribute.vo.DistributeVo;
import com.css.dzj.dzjfxyj.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import dm.jdbc.stat.support.json.JSONString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class DistributeServiceImpl implements DistributeService {

    @Autowired
    DistributeMapper distributeMapper;
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ServiceUtil serviceUtil;
    @Autowired
    private AcquierService acquierService;

    String suserName = "";
    String location = "";
    String address="";
    String orgName = "";

    @Override
    public QueryResults<JgFxyjWarningSignalEntity> selectAll(String fxyjDomainId, String fxyjTitle, String fxyjLevel, String fxyjObjectName, String startTime1, String endTime1, String startTime, String endTime, Pageable pageable) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = (StringUtils.isEmpty(fxyjDomainId)) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (StringUtils.isEmpty(fxyjTitle)) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (StringUtils.isEmpty(fxyjLevel)) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (StringUtils.isEmpty(fxyjObjectName)) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%" + fxyjObjectName.trim() + "%"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse("2010-12-30");
                endDate = sf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(startTime);
                endDate = sf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.between(startDate,endDate));
        }

        if((StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse("2010-12-30");
                endDate = sf.parse(endTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(startTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(startTime1);
                endDate = sf.parse(endTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }
        predicate =ExpressionUtils.and(predicate,q.getState.eq(Constant.YIGET));
        predicate =ExpressionUtils.and(predicate,q.overState.eq(Constant.DAIOVER));
        predicate =ExpressionUtils.and(predicate,q.revertState.eq(Constant.DAIREPLY));
        return jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )//已接收，未结束，（不知道是否已回复）
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public DistributeVo findById(String id) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        JgFxyjWarningSignalEntity fetchOne = jpaQueryFactory
                .selectFrom(q)
                .where(q.id.eq(id)
                )
                .fetchOne();
        DistributeVo distributeVo = new DistributeVo();
        distributeVo.setRiskwarning(fetchOne);

        QJgFxyjFenfaEntity qFenfa=QJgFxyjFenfaEntity.jgFxyjFenfaEntity;
        List<JgFxyjFenfaEntity> list = jpaQueryFactory
                .selectFrom(qFenfa)
                .where(qFenfa.getId.eq(id))
                .orderBy(
                        // 根据创建日期，降序排序
                        qFenfa.creatTime.desc()
                ).fetch();
        distributeVo.setRiskwarningChildren(list);
        return distributeVo;
    }

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<JgFxyjFenfaEntity> getPage(Pageable pageable) {
        QJgFxyjFenfaEntity q=QJgFxyjFenfaEntity.jgFxyjFenfaEntity.jgFxyjFenfaEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        return jpaQueryFactory.selectFrom(q).
                where(predicate).
                orderBy(q.creatTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();
    }

    /**
     * 保存
     * @param riskwarningEdit
     */
    @Override
    @Transactional
    public R saveFenFa(DistributeEditVo riskwarningEdit,HttpServletRequest request) {
        try {
            if(StringUtils.isEmpty(riskwarningEdit)){
                throw new RuntimeException("选择机构为空");
            }

            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                orgName = userInfo.getOrgName();
            }

            JgFxyjWarningSignalEntity acquire = riskwarningEdit.getJgFxyjAcquire();
            JgFxyjFenfaEntity fenfa = riskwarningEdit.getJgFxyjFenfa();
            List<String> fenfaList = riskwarningEdit.getFenfaList();

            JgFxyjFenfaEntity jgFxyjFenfa;
            List<JgFxyjFenfaEntity> list = new ArrayList<>();
            String toOrg = "";
           for(int i=0;i<fenfaList.size();i++){
                jgFxyjFenfa=new JgFxyjFenfaEntity();
                jgFxyjFenfa.setCreatPerson(suserName);
                jgFxyjFenfa.setOperatePerson(suserName);
                jgFxyjFenfa.setOperateOrg(orgName);
                jgFxyjFenfa.setGetId(acquire.getId());
                jgFxyjFenfa.setDisposeResult(fenfa.getDisposeResult());
                jgFxyjFenfa.setDisposeExplain(fenfa.getDisposeExplain());
                jgFxyjFenfa.setFenfaTime(fenfa.getFenfaTime());
                jgFxyjFenfa.setCreatTime(new Date());
                jgFxyjFenfa.setId(UUID.randomUUID().toString());
                jgFxyjFenfa.setFenfaToOrg(fenfaList.get(i));
                list.add(jgFxyjFenfa);
            }
            distributeMapper.saveAll(list);
            updFenFaState(acquire.getId());
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    /**
     * 修改
     * @param jgFxyjFenfaEntity
     */
    @Override
    @Transactional
    public void updFenfa(JgFxyjFenfaEntity jgFxyjFenfaEntity) {

    }
    /**
     * 根据id查询acquire
     * @param id
     * @return
     */
    @Override
    public DistributeEditVo getAcquireById(String id,HttpServletRequest request) {
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String orgName = "";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();
            location = orgName.replace("地震局","");
            address = userInfo.getAddress();
        }
        DistributeEditVo distributeEditVo = new DistributeEditVo();
        JgFxyjWarningSignalEntity acquire = acquierService.findById(id);
        distributeEditVo.setJgFxyjAcquire(acquire);
        JgFxyjFenfaEntity jgFxyjFenfaEntity = new JgFxyjFenfaEntity();
        jgFxyjFenfaEntity.setOperatePerson(suserName);
        jgFxyjFenfaEntity.setOperateOrg(orgName);
        jgFxyjFenfaEntity.setDisposeResult("1");
        jgFxyjFenfaEntity.setFenfaTime(new Date());
        distributeEditVo.setJgFxyjFenfa(jgFxyjFenfaEntity);
        return distributeEditVo;
    }

    /**
     * 修改分发状态
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R updFenFaState(String id) {
        try {
            if(!"".equals(id) && id!=null){
                QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
                jpaQueryFactory.update(q)
                        .set(q.dispenseState, Constant.YIDISTRIBUTE).set(q.dealState,Constant.YIFENFA).set(q.dispensePerson,suserName).set(q.dispenseOrg,orgName).set(q.dispenseTime,new Date())
                        .where(q.id.eq(id))
                        .execute();
                return R.ok();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


}
